package com.pan.service.aspect;

import com.pan.annotation.GoodsExist;
import com.pan.entity.Goods;
import com.pan.entity.Result;
import com.pan.excep.error.ServiceException;
import com.pan.feign.GoodsServerFeign;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
@Component
public class GoodsExistAspect {

    @Resource
    private GoodsServerFeign goodsServerFeign;


    @Pointcut("@annotation(com.pan.annotation.GoodsExist)")
    public void GoodsExistAnnotationCut(){}

    private <T> Integer  indexOf(T[] arr,T target){
        for(int i=0;i<arr.length;i++){
            if (arr[i].equals(target)){
                return i;
            }
        }
        return null;
    }

    @Before("GoodsExistAnnotationCut()")
    public void checkGoodsIdBefore(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        Object target = joinPoint.getTarget();//拦截的目标方法
        String methodName = methodSignature.getMethod().getName();
        Class[] parameterTypes = methodSignature.getParameterTypes();
        Method targetMethod;
        try {
            targetMethod = target.getClass().getMethod(methodName,parameterTypes);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        GoodsExist goodsExist = targetMethod.getAnnotation(GoodsExist.class);
        String goodsIdParameterName = goodsExist.value();
        Object[] args = joinPoint.getArgs();
        String[] parameterNames = methodSignature.getParameterNames();
        Integer index = indexOf(parameterNames,goodsIdParameterName);
        if (index == null){
            throw new ServiceException(500,targetMethod.getName()+" 你这个方法乍没有商品id的参数捏？！！");
        }

        Long goodsId = (Long) args[index];
        Result<Goods> resultGoods = goodsServerFeign.selectById(goodsId);
        if (resultGoods.getCode()!= 200 || resultGoods.getData() == null){
            throw new ServiceException(403,targetMethod.getName()+" 没有该id: " + goodsId + " 的商品呀！！");
        }

    }


}
